package cn.harry.component.security.service;

import cn.harry.component.security.model.SysUserDetails;
import cn.harry.demo.domain.SysUser;
import cn.harry.demo.mapper.SysUserMapper;
import cn.harry.demo.mapper.SysUserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 系统用户认证  service
 *
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;
    private final SysUserRoleMapper sysUserRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            // 获取登录用户信息
            SysUser user = sysUserMapper.selectByUsername(username);
            // 用户不存在、用户停用 等校验 TODO
            Long useId = user.getId();
            // 获取角色
            Set<String> roles = sysUserRoleMapper.listRoleKeyByUserId(useId);
            return new SysUserDetails(user, roles, username);
        } catch (Exception e) {
            log.error("loadUserByUsername error", e);
        }
        return null;
    }
}
